package com.example.netty.common;

import com.example.netty.pojo.Offside;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.QueryApi;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;

import java.util.List;

public class FluxQuery {

    public static  <T> T newFindOne(InfluxDBClient influxDBClient, String bucketName, String startDuration, String measurementName, Class<T> clazz){
        QueryApi queryApi = influxDBClient.getQueryApi();
        String flux = String.format("from(bucket: \"%s\")\n" +
                        "  |> range(start: %s)\n" +
                        "  |> filter(fn: (r) => r[\"_measurement\"] == \"%s\")\n" +
                        "  |> last()" +
                        "  |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")",
                bucketName, startDuration, measurementName);
        List<T> result = queryApi.query(flux,clazz);
        return result.size()==0?null:result.get(0);
    }

    public static <T> void  add(String bucketName, WriteApiBlocking writeApiBlocking,T v){
        writeApiBlocking.writeMeasurement(bucketName,"netty",WritePrecision.MS,v);
    }

    public static void addBatch(String bucketName, WriteApiBlocking writeApiBlocking, List<Offside> offsides){
        writeApiBlocking.writeMeasurements(bucketName,"netty",WritePrecision.MS,offsides);
    }
}
